<?php

namespace App\Console\Commands;

use App\Models\BusinessDistrict;
use App\Models\ChinaArea;
use App\Models\Recruit;
use App\Models\RecruitCategory;
use App\Models\User;
use App\Models\UserVerifyInfo;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class DealCityScript extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'city:jingweidu';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '根据地址获取经纬度';

    public function handle()
    {
        $streets = DB::table('street')->get();
        foreach ($streets as $street) {
            $address = '武汉市' . $street->name;
            $response = $this->requestTencent('address', $address); // 根据地址获取经纬度
            if ($response['status'] == 0) {
                $longitude = $response['result']['location']['lng'] ?? '0.0';
                $latitude = $response['result']['location']['lat'] ?? '0.0';
                DB::table('street')->where('id', '=', $street->id)
                    ->update(['longitude' => $longitude, 'latitude' => $latitude]);
            }
        }
    }

    public function handle5()
    {
        $filePath = 'app/public/recruit/bubble-district.json';
        $files = file_get_contents(storage_path($filePath));
        $files = json_decode($files, true);
        $bubbles = $files['data']['bubbleList'];
        foreach ($bubbles as $bubble) {
            $data[] = [
                'region_name' => $bubble['name'] . '区',
                'latitude'    => $bubble['latitude'],
                'longitude'   => $bubble['longitude'],
            ];
        }
        DB::table('region_center')->insert($data);
    }

    public function handle4()
    {
        $fileName = 'boss-技术项目管理-江夏区';
        $appPath = 'app/public/recruit/' . $fileName . '.json';
        $filePath = storage_path($appPath);
        $jobs = file_get_contents($filePath);
        $jobs = json_decode($jobs, true);
        foreach ($jobs as $job) {
            if (isset($job['address'])) {
                $address = $job['address'];
                $response = $this->requestTencent('address', $address); // 根据地址获取经纬度
                if ($response['status'] == 0) {
                    // 1. 获取经纬度
                    $longitude = $response['result']['location']['lng'] ?? '0.0';
                    $latitude = $response['result']['location']['lat'] ?? '0.0';

                    // 2. 再根据经纬度获取 ”街道“ 信息
                    $lonlat = $latitude . ',' . $longitude;
                    $response = $this->requestTencent('lonlat', $lonlat);
                    $street = '';
                    if ($response['status'] == 0) {
                        $street = $response['result']['address_reference']['town']['title'] ?? '';
                    }

                    $userId = mt_rand(1, 32);
                    $user = User::query()->where('id', '=', $userId)->first(['mobile', 'nickname']);
                    $verifyType = UserVerifyInfo::query()->where('user_id', '=', $userId)->value('type');
                    $salaries = explode('-', $job['salary']);
                    $minSalary = $salaries[0];
                    $maxSalary = $salaries[1];
                    $salaryInfo = ["work_type" => "month", "min_salary" => $minSalary, "max_salary" => $maxSalary];

                    $fileNames = explode('-', $fileName);
                    $recruitCateName = $fileNames[1];
                    $recruitCateId = RecruitCategory::query()->where('name', '=', $recruitCateName)->value('id');
                    $district = $fileNames[2];

                    $data[] = [
                        'user_id'           => $userId,
                        'province'          => '湖北省',
                        'city'              => '武汉市',
                        'district'          => $district,
                        'address'           => $address,
                        'address_detail'    => $address,
                        'street'            => $street,
                        'region_name'       => $street . '附近',
                        'contact_name'      => $user->nickname,
                        'contact_phone'     => $user->mobile,
                        'title'             => $job['title'],
                        'recruit_desc'      => $job['desc'],
                        'longitude'         => $longitude,
                        'latitude'          => $latitude,
                        'recruit_cate_id'   => $recruitCateId,
                        'recruit_cate_name' => $recruitCateName,
                        'verify_type'       => $verifyType,
                        'salary_info'       => json_encode($salaryInfo),
                        'status'            => 2
                    ];
                }
            }
        }
        Recruit::query()->insert($data);
    }

    public function handle3()
    {
        // 查询出地址里包含 、和 / 的数据，然后根据经纬度去获取详细的地理数据
        // 区(district)：result->address_component->district
        // 地标(address)：result->address_component->street
        $recruits = Recruit::query()
            //->select('address', \DB::raw('count(address) as countaddress'), 'longitude', 'latitude')
            //->whereRaw("address like '%/%' OR address LIKE '%、%'")
            ->where('area_name', '=', '')
            //->groupBy('address')
            //->having('countaddress', '>', 1)
            //->limit(1)
            ->get()
            ->toArray();
        foreach ($recruits as $recruit) {
            $ids = Recruit::query()->where('address', '=', $recruit['address'])->pluck('id')->toArray();
            $lonlat = $recruit['latitude'] . ',' . $recruit['longitude'];
            $response = $this->requestTencent('lonlat', $lonlat);
            file_put_contents(storage_path('lonlat/'.$lonlat.".json"), $response);
            $response = json_decode($response, true);
            if ($response['status'] == 0) {
                $tencentDistrict = $response['result']['address_component']['district'] ?? '';
                $tencentAddress = $response['result']['address_component']['street'] ?? '';
                $poiCount = $response['result']['poi_count'] ?? 0;
                if ($poiCount) {
                    $pois = $response['result']['pois'];
                    foreach ($ids as $key => $id) {
                        if (isset($pois[$key])) {
                            $update = [
                                'area_name'         => $tencentAddress, // 区域名称
                                'district'          => $tencentDistrict, // 区
                                'address'           => $pois[$key]['title'], // 地址
                                'address_detail'    => $pois[$key]['address'], // 地址详情
                                'longitude'         => $pois[$key]['location']['lng'],
                                'latitude'          => $pois[$key]['location']['lat'],
                            ];
                            Recruit::query()->where('id', '=', $id)->update($update);
                        }
                    }
                }
            }
        }
    }

    public function handle2()
    {
        $filePath = './经纬度1.txt';
        $file = fopen($filePath, "r"); // 打开文件
        if ($file) {
            while (($line = fgets($file)) !== false) { // 逐行读取文件
                $pattern = '/id为(\d+).*?经度: ([\d.]+), 纬度: ([\d.]+)/';
                if (preg_match($pattern, $line, $matches)) {
                    echo $matches[1] . '-' . $matches[2] . '-' . $matches[3] . PHP_EOL;
                    $id = $matches[1];
                    BusinessDistrict::query()->where('id', '=', $id)->update([
                        'longitude' => $matches[2],
                        'latitude' => $matches[3],
                    ]);
                } else {
                    echo "未找到匹配项";
                }
            }
            fclose($file); // 关闭文件
        }
    }

    /**
     * Execute the console command.
     */
    public function handle1()
    {
        // $recruits = Recruit::query()->where('id', '=', 2063)->first(['id', 'city', 'district', 'address_detail']);

        /*$recruits = Recruit::query()
            ->where('id', '>', 1083)
            ->whereNull('longitude')
            ->get(['id', 'city', 'district', 'address_detail'])
            ->toArray();*/
        $recruits = BusinessDistrict::query()->where('district', '=', '')->get()->toArray();
        $config = [
            'base_uri' => 'https://h5gw.map.qq.com',
            'verify' => false
        ];
        $client = new Client($config);
        foreach ($recruits as $recruit) {
            // $address = $recruit['city'] . $recruit['district'] . $recruit['address_detail'];
            $address = $recruit['city'] . $recruit['area'];
            $options = [
                'query' => [
                    'address' => $address,
                    'key' => 'OB4BZ-D4W3U',
                    'apptag' => 'lbs_geocoder',
                ],
                'headers' => $this->getLonLatHeaders()
            ];
            $response = $client->request('get', '/ws/geocoder/v1', $options);
            $response = $response->getBody()->getContents();
            $response = json_decode($response, true);
            if ($response['status'] == 0) {
                // 获取经纬度
                $longitude = $response['result']['location']['lng'] ?? '空';
                $latitude = $response['result']['location']['lat'] ?? '空';
                $district = $response['result']['address_components']['district'] ?? '空';
                $recruitId = $recruit['id'];
                $msg = 'id为'. $recruitId .', 地址为: ' . $address .', 经度: ' . $longitude . ', '. '纬度: ' . $latitude . PHP_EOL;
                echo $msg;
                file_put_contents('./经纬度2.txt', $msg, FILE_APPEND);
                BusinessDistrict::query()->where('id', $recruitId)->update(
                    ['longitude' => $longitude, 'latitude' => $latitude, 'district' => $district]
                );
            }
        }
    }

    private function requestTencent($type, $params)
    {
        $config = [
            'base_uri' => 'https://h5gw.map.qq.com',
            'verify' => false
        ];
        $client = new Client($config);
        if ($type == 'lonlat') {
            $options = [
                'query' => [
                    'location'  => $params,
                    'get_poi'   => 1,
                    'key'       => 'OB4BZ-D4W3U',
                    'apptag'    => 'lbs_geocoder'
                ],
                'headers' => $this->getAddressInfoHeaders()
            ];
        } else if ($type == 'address') {
            $options = [
                'query' => [
                    'address' => $params,
                    'key' => 'OB4BZ-D4W3U',
                    'apptag' => 'lbs_geocoder',
                ],
                'headers' => $this->getLonLatHeaders()
            ];
        }
        $response = $client->request('get', '/ws/geocoder/v1', $options);
        return json_decode($response->getBody()->getContents(), true);
    }

    private function getAddressInfoHeaders(): array
    {
        return [
            "Accept"             => "*/*",
            "Accept-Language"    => "zh-CN,zh;q=0.9,en;q=0.8",
            "Connection"         => "keep-alive",
            "Origin"             => "https://lbs.qq.com",
            "Referer"            => "https://lbs.qq.com/",
            "Sec-Fetch-Dest"     => "empty",
            "Sec-Fetch-Mode"     => "cors",
            "Sec-Fetch-Site"     => "same-site",
            "User-Agent"         => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36",
            "sec-ch-ua"          => 'Google Chrome";v="123", "Not":A-Brand";v="8", "Chromium";v="123"',
            "sec-ch-ua-mobile"   => "?0",
            "sec-ch-ua-platform" => "Windows"
        ];
    }

    private function getLonLatHeaders(): array
    {
        return [
            "Accept"             => "*/*",
            "Accept-Language"    => "zh-CN,zh;q=0.9,en;q=0.8",
            "Connection"         => "keep-alive",
            "Origin"             => "https://lbs.qq.com",
            "Referer"            => "https://lbs.qq.com/",
            "Sec-Fetch-Dest"     => "empty",
            "Sec-Fetch-Mode"     => "cors",
            "Sec-Fetch-Site"     => "same-site",
            "User-Agent"         => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36",
            "sec-ch-ua"          => 'Google Chrome";v="123", "Not:A-Brand";v="8", "Chromium";v="123"',
            "sec-ch-ua-mobile"   => "?0",
            "sec-ch-ua-platform" => "Windows"
        ];
    }
}
